import React, { useRef, useEffect, useState } from 'react';
import Table from '../../components/Table';

interface DataType extends Record<string, unknown> {
  id: number;
  name: string;
  age: number;
  address: string;
}

type ColumnType = {
  title: string;
  key: string;
  dataIndex?: string;
  render?: (_: unknown, record: DataType) => JSX.Element;
}

const ExamplePage: React.FC = () => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [isDrawing, setIsDrawing] = useState(false);
  const [lastPosition, setLastPosition] = useState<{x: number, y: number} | null>(null);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;

    const context = canvas.getContext('2d');
    if (!context) return;

    // 设置画笔样式
    context.strokeStyle = '#000';
    context.lineWidth = 2;
    context.lineCap = 'round';
  }, []);

  const startDrawing = (e: React.MouseEvent) => {
    setIsDrawing(true);
    setLastPosition({
      x: e.nativeEvent.offsetX,
      y: e.nativeEvent.offsetY
    });
  };

  const draw = (e: React.MouseEvent) => {
    if (!isDrawing || !canvasRef.current || !lastPosition) return;

    const context = canvasRef.current.getContext('2d');
    if (!context) return;

    context.beginPath();
    context.moveTo(lastPosition.x, lastPosition.y);
    context.lineTo(e.nativeEvent.offsetX, e.nativeEvent.offsetY);
    context.stroke();

    setLastPosition({
      x: e.nativeEvent.offsetX,
      y: e.nativeEvent.offsetY
    });
  };

  const stopDrawing = () => {
    setIsDrawing(false);
    setLastPosition(null);
  };

  const columns: ColumnType[] = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '年龄',
      dataIndex: 'age',
      key: 'age',
    },
    {
      title: '地址',
      dataIndex: 'address',
      key: 'address',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: unknown, record: DataType) => (
        <button 
          className="table-action-btn"
          onClick={() => console.log(record)}
        >
          查看
        </button>
      ),
    },
  ];

  const dataSource: DataType[] = [
    {
      id: 1,
      name: '张三',
      age: 32,
      address: '北京市朝阳区',
    },
    {
      id: 2,
      name: '李四',
      age: 42,
      address: '上海市浦东新区',
    },
  ];

  return (
    <div>
      <canvas
        ref={canvasRef}
        width={800}
        height={600}
        style={{
          border: '1px solid #ccc',
          margin: '20px'
        }}
        onMouseDown={startDrawing}
        onMouseMove={draw}
        onMouseUp={stopDrawing}
        onMouseLeave={stopDrawing}
      />
      
      <Table<DataType & Record<string, unknown>>
        columns={columns}
        dataSource={dataSource}
        loading={false}
        rowKey="id"
      />
    </div>
  );
};

export default ExamplePage; 